package com.seis_645.appTesting;

import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;

public class CarActivity extends ListActivity {
	/** Called when the activity is first created. */
	private CarDataSource datasource;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.car_main);
		final ListView lv = getListView();
		datasource = new CarDataSource(this);
		datasource.open();
		List<Car> values = datasource.get_all_cars();
		ArrayAdapter<Car> adapter = new ArrayAdapter<Car>(this,
				android.R.layout.simple_list_item_1, values);

		lv.setAdapter(adapter);

		lv.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> a, View v, int position,
					long id) {
				Car car = (Car) lv.getItemAtPosition(position);
				goToCar(car);
			}
		});

	}
	
	protected void goToCar(Car car) {
		TabGroupActivity parentActivity = (TabGroupActivity) getParent();
		Intent carInfo = new Intent(getParent(), CarInfoActivity.class);
		carInfo.putExtra("car_id",car.get_id());
		parentActivity.startChildActivity("CarInfoActivity",carInfo);
		return;
	}

	@Override
	protected void onDestroy() {
		datasource.close();
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		datasource.close();
		super.onPause();
	}

	@Override
	protected void onResume() {
		datasource.open();
		super.onResume();
	}

	public void onClick(View view) {
		TabGroupActivity parentActivity = (TabGroupActivity) getParent();
		switch (view.getId()) {
		case R.id.add_button:
			Intent saveCar = new Intent(getParent(), SaveCarActivity.class);
			parentActivity.startChildActivity("SaveCarActivity", saveCar);
			break;
		case R.id.compare_button:
			Intent compareCar = new Intent(getParent(),CarCompareActivity.class);
			parentActivity.startChildActivity("CarCompareActivity",compareCar);
		}
		return;
	}
}